<template>
  <div class="home">    
    <DrawBoard v-show="statue==='draw'" @draw-begin="onDrawBegin" @on-draw="onDraw" @draw-end="onDrawEnd" @one-draw="onOneDraw"/>
    <canvas v-show="statue==='guess'" ref="drawCanvas" width="375px" height="320px"></canvas>
  </div>
</template>

<script>
// @ is an alias to /src
const ServerCanvasWidth = 375;
import Socket from "@/util/Socket.js";
import DrawBoard from "@/components/DrawBoard.vue";
import Scale from "@/util/scale.js";
import CanvasDraw from "@/util/canvasDraw.js";
let ws;
let ctx;
export default {
  name: "home",
  data() {
    return {
      statue:'draw'
    };
  },
  methods: {
    onDrawBegin({ x, y, color, width }) {
      let posArr = Scale.localToServer([{ x, y }]);
      let data = {
        op: "draw-begin",
        drawData: {
          width,
          color,
          posArr
        }
      };
      Socket.send(JSON.stringify(data));
    },
    onDraw({ x, y }) {
      let posArr = Scale.localToServer([{ x, y }]);
      let data = {
        op: "on-draw",
        drawData: {
          posArr
        }
      };
      Socket.send(JSON.stringify(data));
    },
    onDrawEnd({ x, y }) {
      let posArr = Scale.localToServer([{ x, y }]);
      let data = {
        op: "draw-end",
        drawData: {
          posArr
        }
      };
      Socket.send(JSON.stringify(data));
    },
    onOneDraw(localStrokeData) {
      //console.log(localStrokeData);
      //ws.send(JSON.stringify(Scale.localToServer(localStrokeData)));
    },
    drawByStrokeData(ctx, strokeData) {
      CanvasDraw.drawByStrokeData(ctx, strokeData);
    },
    listenSocket() {
      Socket.addLisener("draw-begin", serverData => {        
        const drawData = serverData.drawData;
        const posArr = Scale.serverToLocal(drawData.posArr);
        CanvasDraw.beginDraw(ctx, {
          lineWidth: drawData.width,
          color: drawData.color,
          x: posArr[0].x,
          y: posArr[0].y
        });
      });

      Socket.addLisener("on-draw", serverData => {
        const drawData = serverData.drawData;
        const posArr = Scale.serverToLocal(drawData.posArr);
        CanvasDraw.drawAPoint(ctx, { x: posArr[0].x, y: posArr[0].y });
      });

      Socket.addLisener("draw-path", serverData => {
        const drawData = serverData.drawData;
        const posArr = Scale.serverToLocal(drawData.posArr);
        CanvasDraw.drawByStrokeData(ctx, {
          lineWidth: drawData.width,
          color: drawData.color,
          posArr
        });
      });
    }
  },
  mounted() {
    let xs = document.body.clientWidth / this.$refs.drawCanvas.width;
    this.$refs.drawCanvas.width = document.body.clientWidth;
    this.$refs.drawCanvas.height = this.$refs.drawCanvas.height * xs;
    ctx = this.$refs.drawCanvas.getContext("2d");
    this.listenSocket();
  },
  components: {
    DrawBoard
  }
};
</script>
